package com.ly.mpayment.rest.up.yishuo;

import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.Base64;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import com.ly.mpayment.rest.up.util.Util;
import org.apache.log4j.Logger;
import org.mortbay.util.MultiMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Component
@Path("yishuo")
public class YiShuoRest {
    Logger logger = Logger.getLogger(YiShuoRest.class);

    @Autowired
    IUporderService upOrderService;

    @Autowired
    IDownRechargeFlowService flowService;

    @Autowired
    IDownShopInfoService shopService;

    @Autowired
    IUpShopInfoService upShopInfoService;


    @Path("callBack")
    @POST
    public String callBack(@RequestBody String data) {
        logger.info("yishuo_callback:" + data);
        if (!StringUtils.isBlank(data)) {
            MultiMap multiMap = Util.parceString(data);
            UpOrder order = upOrderService.findById(multiMap.getString("extOrderId"));
            if(order == null){
                logger.info("订单不存在:"+data);
                return "订单不存在";
            }
            final UpShopInfo upShopInfo = this.upShopInfoService.findByUserId(order.getUserOrder().getUseruuid());
            if(upShopInfo == null){
                logger.info("渠道用户不存在:"+data);
                return "failt";
            }

            //extOrderId+orderId+state+(商户的md5key)
            if(!multiMap.getString("sign").equals(MD5.md5(multiMap.getString("extOrderId")+
                    multiMap.getString("orderId")
                    +multiMap.getString("state")+upShopInfo.getUpkey()).toLowerCase())){
                logger.info("签名错误:"+data);
                return "failt";
            }

            if (order != null && multiMap.getString("state").equals("4") && order.getStatus() == Config.status[0]) {
                order.setRemark(multiMap.containsKey("orderId") ? multiMap.getString("orderId") : multiMap.getString("msg"));
                RechargeRest.successUpOrder.add(order);
                return "OK";
            } else if (order != null && order.getStatus() == Config.status[0] && multiMap.getString("state").equals("5")) {
                order.setRemark(multiMap.getString("msg"));
                RechargeRest.failtUpOrder.add(order);
                return "OK";
            } else {
                this.upOrderService.addOrderMsg(order,multiMap.getString("msg"));
                logger.info("yishuo_not_found_order:" + multiMap.getString("tel") + "," + (order == null ? "" : order.getUpphonenum()));
            }
        }
        return "0";
    }


    /**
     * 订单提交
     *
     * @param order
     * @param shop
     */
    public void commitOrder(UpOrder order, UpShopInfo shop) {

        JSONObject data = new JSONObject();
        data.put("merchantId",shop.getAppId());
        data.put("amt",order.getUpShopPro().getUpfacevalue());
        data.put("extOrderId", order.getUporderuuid());
        data.put("phone", order.getUpphonenum());
        data.put("notifyUrl",shop.getOrderCallAddress());
        if(order.getUpShopPro().getProvincialInformation().getProvinceuuid()
                .equals("e09563cf-9f98-11e7-9dc0-fcaa1456507e")){
            data.put("sourceType",Config.proCity);
        }
        //amt +extOrderId+ merchantId + notifyUrl +phone+（timeOut）+（商户的md5key
        data.put("md5",MD5.md5(order.getUpShopPro().getUpfacevalue()+order.getUporderuuid()
                +shop.getAppId()+shop.getOrderCallAddress()+order.getUpphonenum()+shop.getUpkey()));
        String result = HttpClient.postUrl(shop.getOrderCommitAddress(), StringSort.jsonToString(data));
        logger.info("commitOrder_yishuo:" + result + ":" + StringSort.jsonToString(data));
        if (!StringUtils.isBlank(result)) {
            try{
                JSONObject json = JSONObject.parseObject(result);
                if (json.containsKey("code") && json.getString("code").equals("0")) {
                    this.upOrderService.updateUpOrderMsg(order,json.getString("code"),  json.getString("msg"));
                } else if (json.containsKey("code") && errorCode.contains(json.getString("code"))){
                    order.setRemark(json.getString("msg"));
                    RechargeRest.failtUpOrder.add(order);
                } else {
                    upOrderService.addOrderMsg(order, json.getString("msg"));
                }
            }catch (Exception e){
                e.printStackTrace();
                upOrderService.updateUpOrderArtificial(order,"","提单失败,人工");
            }
        } else {
            this.upOrderService.updateUpOrder(order, "");
            logger.info("commitOrder_error:" + order.getUpphonenum());
        }
    }

    /**
     * 1 操作失败
     * 100000 订单已存在
     * 200000 账户不存在
     * 200002 账户信息校验失败 200003 ip 不符 200004 账户已经被锁定
     */
    Set<String> errorCode = new HashSet<String>(){{
        add("1");
        add("100000");
        add("200000");
        add("200002");
        add("200003");
        add("200004");
    }};

    /**
     * 订单查询
     *
     * @param upOrder
     * @param shopInfo
     */
    public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {

        JSONObject data = new JSONObject();
        data.put("merchantId",shopInfo.getAppId());
        data.put("extOrderId",upOrder.getUporderuuid());
        //签名 extOrderId+ merchantId+(商户的md5key)
        data.put("sign",MD5.md5(upOrder.getUporderuuid()+shopInfo.getAppId()+shopInfo.getUpkey()));
        String result = HttpClient.postUrl(shopInfo.getOrderStatusAddress(),StringSort.jsonToString(data));
        logger.info("yishuoqueryOrder:" + upOrder.getUpphonenum() + ":" + result+","+data);
        if (!StringUtils.isBlank(result)) {
            //{"szOrderId":"2c99e0237941a983017941aa1f5d0004","fSalePrice":47.7,"nRtn":5013,"szRtnCode":"fail","szRtnMsg":""}
            JSONObject jsonD = JSONObject.parseObject(result);
            if (jsonD.containsKey("code") && jsonD.getString("code").equals("0")) {
                UpOrder order = upOrderService.findById(upOrder.getUporderuuid());
                if (order != null && jsonD.getString("data").equals("4") && order.getStatus() == Config.status[0]) {
                    order.setRemark( jsonD.containsKey("ext") ? jsonD.getString("ext") :
                            jsonD.containsKey("msg") ? jsonD.getString("msg") : jsonD.getString("data"));
                    RechargeRest.successUpOrder.add(order);
                } else if (order != null && order.getStatus() == Config.status[0] && jsonD.getString("data").equals("5") ) {
                    order.setRemark( jsonD.containsKey("ext") ? jsonD.getString("ext") : jsonD.getString("msg"));
                    RechargeRest.failtUpOrder.add(order);
                } else {
                    this.upOrderService.addOrderMsg(order,jsonD.getString("msg"));
                    logger.info("yishuo_not_found_order:" + order.getUpphonenum());
                }
            } else {
                logger.info("yishuo_not_found_order:" + upOrder.getUpphonenum());
            }
        }
    }
}
